package com.eso.frame;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.util.Map;

/**
 * 组件管理工具类
 * User: Noah.Rong
 * Version: 0.1,  2012-05-22 16:04
 */
public class ComponentManager {

    private Logger logger = Logger.getLogger(ComponentManager.class);

    private static ComponentManager su = new ComponentManager();
    private static ApplicationContext context = null;
    public Boolean initialized = Boolean.FALSE;

    private ComponentManager() {
    }

    public static ComponentManager getInstance() {
        return su;
    }

    private ApplicationContext getApplicationContext() {
        return context;
    }

    public void setServletContext(final ServletContext sc) {
        context = WebApplicationContextUtils.getWebApplicationContext(sc);
        this.initialized = Boolean.TRUE;
    }

    public void publishEvent(ApplicationEvent event) {
        this.getApplicationContext().publishEvent(event);
    }

    public Object getComponent(Class clazz) {
        return this.getBean(clazz.getName());
    }

    public Object getBean(String beanName) {
        Object bean = null;
        try {
            bean = context.getBean(beanName);
        } catch (Exception e) {
            logger.info("beanId of " + beanName + " has not found");
        }
        return bean;
    }

    public Object findBeanByType(Class clazz) {
        Object bean = null;
        try {
            bean = context.getBean(clazz);
        } catch (Exception e) {
            logger.info("bean of " + clazz + " has not found");
        }

        return bean;
    }

    public Boolean containsBean(String beanName) {
        return context.containsBean(beanName);
    }

    public Map getBeansOfType(Class clazz) {
        return context.getBeansOfType(clazz);
    }
}
